import React, { Component } from 'react'
import { connect } from 'react-redux'
import { changeCount } from '../../../actions/index'

class Cart extends Component {
    change = (e, id) => {
        this.props.changeFlag(e.target.checked, id)
    }
    allCheck=(e)=>{
        this.props.allcheck(e.target.checked);
    }
    render() {
        return (
            <div className="wrap cart-page">
                {
                    this.props.cartList.map(item => {
                        return (
                            <dl key={item.id} className="items">
                                <p><input type="checkbox" checked={item.flag} onChange={(e) => this.change(e, item.id)} /></p>
                                <dt>
                                    <img src={item.img} alt="" />
                                </dt>
                                <dd>
                                    <h2>{item.name}</h2>
                                    <p>单价：{item.price}</p>
                                    <p>数量：
                                    <button onClick={() => this.props.changeCount(item.id, item.count - 1)}>-</button>
                                        {item.count}
                                        <button onClick={() => this.props.changeCount(item.id, item.count + 1)}>+</button>
                                    </p>
                                </dd>
                            </dl>
                        )
                    })
                }
                {
                    this.props.cartList.length?
                    <p className="cart-p">
                    <span><input type="checkbox" checked={this.props.allC} onChange={(e) => this.allCheck(e)} />全选</span>
                    <b>总价:
                    {
                            this.props.cartList.reduce((prev, val) => {
                                return val.flag ? (prev + val.count * val.price) : prev
                            }, 0)
                        }
                    </b>
                </p> : null
                }
            </div>
        )
    }
}



let mapState = state => {
    return {
        cartList: state.cart.cartList,
        allC : state.cart.allC
    }
}

let mapDispatch = dispatch => {
    return {
        changeCount(id, count) {
            dispatch(changeCount(id, count))
        },
        changeFlag(value, id) {
            dispatch({ type: "CHANGE_FLAG", value, id })
        },
        allcheck(value){
            dispatch({type :"ALL_CHECK" ,value})
        }
    }
}

export default connect(mapState, mapDispatch)(Cart)
